# coding=utf8
# 全世界最帅的帅哥
from flask_restful import Resource, reqparse
from comment.utils.decorators import login_required
from comment.modules.account import Account
from flask import g, current_app
from comment.modules.expected_return import ExpectedReturn
from datetime import datetime
from comment.modules import db
from comment.modules.invest_record import InvestRecord
from comment.modules.deal_record import DealRecord
from comment.utils.gen_trans_id import generate_trans_id
from .const import DealType


class InvestIncomeResource(Resource):
    method_decorators = [login_required]

    # 某个预期收益到期之后，获取当前的收益
    def post(self):
        rp = reqparse.RequestParser()
        rp.add_argument("return_id", required=True)  # 指定预期收益的ID

        args = rp.parse_args()
        return_id = args.return_id

        user_id = g.user_id
        # 根据登陆的用户查询资金账户对象
        account = Account.query.filter(Account.userId == user_id).first()
        # 查询当前指定的预期收益对象
        expect_income = ExpectedReturn.query.filter(ExpectedReturn.userId == user_id).first()

        if expect_income:
            # 判断当前的预期收益是否可以获取收益
            cur_date = datetime.now().date()
            expect_date = expect_income.expectedDate.date()
            # 如果当前日期大于等于投资到期的日期
            if cur_date >= expect_date:
                try:
                    # 查出对应的投资记录对象
                    invest = InvestRecord.query.filter(InvestRecord.pId == expect_income.investRecord).first()
                    invest.pStatus = 2  # 修改投资记录的状态

                    # 修改用户的资金账户
                    account.interestA += expect_income.expectedMoney  # 已赚取利息
                    account.interestTotal -= expect_income.expectedDate  # 总计代收利息
                    account.investmentW -= invest.pAmount  # 总计代收本金
                    account.frozen -= invest.pAmount  # 账户总计冻结金额
                    before_balance = account.balance
                    account.balance += expect_income.expectedDate + invest.pAmount  # 账户可用余额
                    account.total += expect_income.expectedMoney  # 账户总额

                    # 创建交易流水号
                    deal_num = generate_trans_id(DealType.income.name)
                    # 新增一条交易记录 # aReceiveOrPay0代表收钱 1代表付钱
                    deal_log = DealRecord(aUserId=user_id, aReceiveOrPay=0,aTransferSerialNo=deal_num,
                                          aTransferStatus=1, aBeforeTradingMoney=before_balance,
                                          aAmount=expect_income.expectedDate, aAfterTradingMoney=account.balance,
                                          aDescription="提取收益", aType=DealType.income.value)
                    db.session.add(deal_log)
                    db.session.commit()
                    return {"msg": "提取收益成功！"}

                except Exception as e:
                    current_app.logger.error(e)
                    db.session.rollback()
                    return {"message": "系统出错"}, 500
            else:
                return {"msg": "投资未到预计收益日", "code": 20001}
        else:
            return {"message": "没有找到对应的预期收益"}, 401
